package sm.pzavoli.mercato;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sm.pzavoli.mercato.model.Ticker;
 
import android.os.AsyncTask;
import android.util.Log;
import android.widget.SimpleAdapter;
 
public class JSONParser extends AsyncTask<String, Void, ArrayList<Ticker>> {
 
    InputStream is = null;
    JSONObject jObj = null;
    String json = "";
    List<HashMap<String, String>> tickerAutoComplete;
    SimpleAdapter adapterAutoComplete;
    ICallBackTask lanciatore = null;
    
    static final String url = "http://d.yimg.com/aq/autoc?region=IT&lang=it-IT&callback=YAHOO.util.ScriptNodeDataSource.callbacks"; 
    // &query=fiat
    // constructor
    public JSONParser(List<HashMap<String, String>> tickerAutoComplete, SimpleAdapter adapterAutoComplete,
    		ICallBackTask lanciatore) {
    	this.tickerAutoComplete = tickerAutoComplete;
    	this.adapterAutoComplete = adapterAutoComplete;
    	this.lanciatore = lanciatore;
    }
 
	@Override
    // three dots is java for an array of strings
	protected ArrayList<Ticker> doInBackground(String... args) {
		if ( args.length > 0) {
			Log.d("gottaGo", "doInBackground");
			ArrayList<Ticker> arr = new ArrayList<Ticker>(0);
			JSONObject json = getJSONFromUrl(args[0]);
    		try {
    			tickerAutoComplete.clear();
    			JSONArray jsonres = json.getJSONObject("ResultSet").getJSONArray("Result");
    			for ( int i = 0; i < jsonres.length(); i++) {
    				String symbol = jsonres.getJSONObject(i).getString("symbol");
    				String name = jsonres.getJSONObject(i).getString("name");
    				HashMap<String, String> map = new HashMap<String, String>();
        	        map.put("Symbol", "" + symbol);  
        	        map.put("Nome", "" + name);  
    				tickerAutoComplete.add(map);
    			}
    			return arr;
    		} catch(Exception e) {
    			e.printStackTrace();
    			Log.e("JSONParser","Errore in lettura tickers da Yahoo."+e.getMessage());
    			return null;
    		}			
		}
		return null;
	}

	@Override
	protected void onPostExecute(ArrayList<Ticker> result) {
		Log.d("YourApp", "onPostExecute : " + result.size());
		//	update the adapter
		adapterAutoComplete.notifyDataSetChanged();
		lanciatore.onTaskFinished(this);
		Log.d("YourApp", "onPostExecute : autoCompleteAdapter" + adapterAutoComplete.getCount());
	}	
	
	@Override
	protected void onCancelled() {
		super.onCancelled();
		tickerAutoComplete.clear();
		lanciatore.onTaskFinished(this);
	}
	
    public JSONObject getJSONFromUrl(String typed) {
 
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            typed = typed.replaceAll(" ", "%20");
            HttpGet httpGet = new HttpGet(url+"&query="+typed);
 
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
            // Elimino la parte iniziale e finale
            json = json.replace("YAHOO.util.ScriptNodeDataSource.callbacks(","").trim();
            json = json.substring(0,json.length() - 2);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
 
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
 
        // return JSON String
        return jObj;
 
    }
}